package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.MetaData;


/**
 * Servlet implementation class AllQuestionListServlets
 * This servlet is responsible for getting all the questions which are to displayed on the Questions .jsp page
 * it will also dispatch the entire metaData associated with each question on the same page 
 * which includes the answers, date of posting, time, associated tags with each question
 * which can then be retrieved on the questions.jsp page as per the requirement.
 * 
 * @author team MetaGranth
 *
 */
public class AllQuestionListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AllQuestionListServlet() {
        super();
 
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}
	
	/**
	 * this function will get all the questions which are to displayed on the Questions .jsp page by calling getAllQuestions
	 * function at the service layer.
	 * On sucess dispatched the metaDataList to questions.jsp page
	 * else to errorPage.jsp.
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
				if(session.getAttribute("userId")!=null){
				try{
					//gets the metaDataList of all questions to displayed by getAllQuestions() function
				ArrayList<MetaData> metaDataList=QuestionService.getAllQuestions();
				request.setAttribute("metaDataList", metaDataList);
				//dispatches the metaDataList to questions.jsp page
				request.getRequestDispatcher("questions.jsp").forward(request, response);
			}catch(Exception exception) {
				request.setAttribute("errormsg", exception.getMessage());
				request.getRequestDispatcher("errorPage.jsp").forward(request, response);
			}
		}else {
			response.sendRedirect("index.jsp");
	}
	}
}
